package cn.org.spring.wechar.interceptor;

import cn.org.spring.wechar.bean.Result;
import cn.org.spring.wechar.config.BasicInfo;
import cn.org.spring.wechar.utils.CacheUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author： 谢辉
 * @date： 2021/5/10
 * @email: xieh_mail@163.com
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */

@Slf4j

@Component
public class LoginUserInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    CacheUtil cacheUtil;

    @Autowired
    BasicInfo basicInfo;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("request.getRequestURI():" + uri);
        //String cookieValue = CookieUtils.getCookieValue(request, "wechat-token");
        // 获取请求头
        String cookieValue = request.getHeader("wechat-token");
        Object o = cacheUtil.get("wechatuser:" + cookieValue);
        log.info("LoginUserInterceptor拦截器从redis获取信息【{}】", String.valueOf(o));
        if (o == null) {
            if (isAjax(request)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter pw = response.getWriter();
                pw.write(JSONObject.toJSONString(Result.fail("请先登录")));
                pw.flush();
                pw.close();
                log.info("LoginUserInterceptor拦截器发现是ajax请求并且未登录，直接响应json数据");
                return false;
            } else {
                log.info("LoginUserInterceptor拦截器发现未登录直接转发登录页面");
                //request.getRequestDispatcher("/login").forward(request, response);
                response.sendRedirect(basicInfo.getUrlPrefix() + "/login");
                return false;
            }
        } else {
            log.info("LoginFilter拦截器检测用户已经登录，直接放行");
            return true;
        }

    }

    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}

